<template>
  <div>
    <el-card>
      <el-form
        ref="ruleForm"
        :rules="rules"
        :model="testForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="学科" prop="subjectID">
          <el-select
            @change="getDirecotrysList"
            placeholder="请选择"
            v-model="testForm.subjectID"
          >
            <el-option
              v-for="item in subjectsList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="目录" prop="catalogID">
          <el-select placeholder="请选择" v-model="testForm.catalogID">
            <el-option
              v-for="item in directorysList"
              :key="item.id"
              :label="item.directoryName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="企业" prop="enterpriseID">
          <el-select placeholder="请选择" v-model="testForm.enterpriseID">
            <el-option
              v-for="item in companysList"
              :key="item.id"
              :label="item.company"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="城市" prop="province">
          <el-select
            class="txt"
            v-model="testForm.province"
            @change="changeProvince"
          >
            <el-option
              v-for="item in provinces"
              :key="item.id"
              :value="item.pro"
              :label="item.pro"
            >
            </el-option>
          </el-select>
          <el-select class="txt" v-model="testForm.city">
            <el-option
              v-for="item in city"
              :key="item.id"
              :value="item.pro"
              :label="item.pro"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="方向" prop="direction">
          <el-select placeholder="请选择" v-model="testForm.direction">
            <el-option
              v-for="(item, index) in directionList"
              :key="index"
              :value="item"
              :label="item"
            ></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="题型" prop="questionType">
          <!-- 0:单选  1：1   2：2-->
          <el-radio-group v-model="testForm.questionType">
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <el-form-item label="难度" prop="difficulty">
          <el-radio-group v-model="testForm.difficulty">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>

        <el-form-item label="题干" prop="question">
          <quill-editor v-model="testForm.question" :options="editorOption" />
          <div v-html="data"></div>
        </el-form-item>

        <el-form-item v-show="testForm.questionType != 3">
          <el-row v-for="(item, index) in testForm.options" :key="index">
            <el-radio-group v-model="isRight" v-if="testForm.questionType == 1">
              <el-radio :label="item.code"></el-radio>
            </el-radio-group>
            <el-checkbox-group
              v-model="isRightList"
              style="display: inline-block"
              v-else-if="testForm.questionType == 2"
            >
              <el-checkbox :label="item.code"></el-checkbox>
            </el-checkbox-group>

            <el-input
              class="txt240"
              v-model="item.title"
              style="margin-left: 10px"
            ></el-input>
            <!-- <Image-upload></Image-upload> -->
            <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <template v-if="item.img">
                <img :src="item.img" class="avatar" />
                <i
                  class="el-icon-close close"
                  @click="removeImg($event, index)"
                ></i>
              </template>

              <template v-else>
                <span class="span" @click="sureNumber(index)">上传图片</span>
              </template>
            </el-upload>
          </el-row>
          <el-button
            type="danger"
            @click="addQuestion"
            :disabled="testForm.questionType != '2'"
            >+增加选项与答案</el-button
          >
        </el-form-item>

        <el-form-item label="解析视频">
          <el-input v-model="testForm.videoURL"></el-input>
        </el-form-item>

        <el-form-item label="答案解析" prop="answer">
          <quill-editor v-model="testForm.answer" :options="editorOption" />
          <div v-html="data"></div>
        </el-form-item>

        <el-form-item label="题目备注" prop="remarks">
          <textarea
            v-model="testForm.remarks"
            style="width: 500px; border-radius: 4px"
            rows="4"
          />
        </el-form-item>

        <el-form-item label="试题标签" prop="tags">
          <el-select
            multiple
            filterable
            placeholder="请选择试题标签"
            v-model="testForm.tags"
          >
            <el-option
              v-for="item in tagsList"
              :key="item.id"
              :label="item.tagName"
              :value="item.tagName"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="addDepartments"
            >确定提交</el-button
          ></el-form-item
        >
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { provinces, citys1 } from "@/api/hmmm/citys.js";
import { subjectsList } from "@/api/hmmm/subjects";
import { simple, detail } from "@/api/hmmm/directorys";
import { list } from "@/api/hmmm/companys";
import { tagsList } from "@/api/hmmm/tags";
import { questionType, difficulty, direction } from "@/api/hmmm/constants";
import {
  addQuestion,
  addQuestionDetail,
  editQuestionDetail,
} from "@/api/hmmm/questions";

import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import { quillEditor } from "vue-quill-editor";

import quillConfig from "@/quill-config.js";
export default {
  components: {
    quillEditor,
  },
  data() {
    return {
      province: "",
      city: "",
      content: "",
      editorOption: quillConfig,
      data: "",
      // 表单数据
      testForm: {
        subjectID: "", // 学科
        catalogID: "", // 目录
        enterpriseID: "", // 企业名称
        province: "", // 城市
        city: "", // 地区
        direction: "", // 方向
        questionType: 1, // 题型
        difficulty: 1, // 难度
        question: "", // 题干
        options: [
          {
            code: "A", // 代码
            title: "123", // 标题
            img: "",
            isRight: false, // 是否正确答案
          },
          {
            code: "B", // 代码
            title: "123", // 标题
            img: "",
            isRight: false, // 是否正确答案
          },
          {
            code: "C", // 代码
            title: "123", // 标题
            img: "",
            isRight: true, // 是否正确答案
          },
          {
            code: "D", // 代码
            title: "123", // 标题
            img: "",
            isRight: true, // 是否正确答案
          },
        ], // 选项
        videoURL: "", // 解析视频
        answer: "", // 答案解析
        remarks: "", // 题目备注
        tags: "", // 试题标签
      },
      // 校验规则
      rules: {
        subjectID: [
          { required: true, message: "这是必填项", trigger: "change" },
        ],
        catalogID: [{ required: true, message: "这是必填项", trigger: "blur" }],
        enterpriseID: [
          { required: true, message: "这是必填项", trigger: "blur" },
        ],
        province: [{ required: true, message: "这是必填项", trigger: "blur" }],
        direction: [{ required: true, message: "这是必填项", trigger: "blur" }],
        questionType: [
          { required: true, message: "这是必填项", trigger: "blur" },
        ],
        difficulty: [
          { required: true, message: "这是必填项", trigger: "blur" },
        ],
        question: [{ required: true, message: "这是必填项", trigger: "blur" }],
        videoURL: [{ required: true, message: "这是必填项", trigger: "blur" }],
        answer: [{ required: true, message: "这是必填项", trigger: "blur" }],
        tags: [{ required: true, message: "这是必填项", trigger: "blur" }],
        remarks: [{ required: true, message: "这是必填项", trigger: "blur" }],
      },
      number: "", // 记录点击了第几个图片
      subjectsList: [],
      directorysList: [],
      companysList: [],
      tagsList: [],
      directionList: direction,
      difficulty,
      questionType,
    };
  },
  created() {
    this.getProvince();
    this.getList();
    this.getCompanyList();
    this.addQuestionDetail();
  },
  computed: {
    // 设置计算属性  计算哪个是正确答案
    isRight: {
      get() {
        let num;
        this.testForm.options.forEach((item) => {
          if (item.isRight) {
            num = item;
          }
        });
        return num.code;
      },
      set(val) {
        this.testForm.options.forEach((item) => {
          if (item.code === val) {
            item.isRight = true;
          } else {
            item.isRight = false;
          }
        });
      },
    },

    isRightList: {
      get() {
        let num = [];
        this.testForm.options.forEach((item) => {
          if (item.isRight) {
            num.push(item.code);
          }
        });
        return num;
      },
      set(val) {
        this.testForm.options.forEach((item) => {
          item.isRight = false;
        });
        this.testForm.options.forEach((item) => {
          val.forEach((item1) => {
            if (item.code === item1) {
              item.isRight = true;
            }
          });
        });
      },
    },
  },
  methods: {
    // 上传图片
    handleAvatarSuccess(res, file) {
      this.$set(this.testForm.options, this.number, {
        ...this.testForm.options[this.number],
        img: URL.createObjectURL(file.raw),
      });
    },

    // 定义图片格式
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    // 表单提交按钮
    addDepartments() {
      // 逻辑代码
      // 判断有无id，
      // 1、有id，调用修改接口
      // 2、没有id ，调用增加接口
      // 3、最后表单置空

      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.testForm.questionType = this.testForm.questionType + "";
          this.testForm.difficulty = this.testForm.difficulty + "";
          if (!this.testForm.id) {
            const res = await addQuestion({
              ...this.testForm,
              tags: this.testForm.tags.join(),
            });
            this.$message({
              type: "success",
              message: "上传成功！",
            });
            this.testForm = {};
          } else {
            const res = await editQuestionDetail({
              ...this.testForm,
              tags: this.testForm.tags.join(),
            });
            this.$message({
              type: "success",
              message: "修改成功！",
            });
          }
          this.$refs.ruleForm.resetFields();
          this.testForm = {};
        } else {
          console.log("error submit!!");
          return false;
        }
      });
      this.$router.push({ name: "questions-list" });
    },

    // 获取省份 下拉
    getProvince() {
      this.provinces = provinces(); //这个是获取省份下拉
    },

    // 当省份变化的时候  拿到一个值
    changeProvince(val) {
      this.city = citys1(val);
    },

    // 删除图片操作
    removeImg(e, index) {
      this.testForm.options[index].img = "";
      e.stopPropagation();
    },

    // 确定number  用来确定点击了第几个图片  进行赋值
    sureNumber(index) {
      this.number = index;
    },

    // 获取学科简单列表
    async getList() {
      const res = await subjectsList();
      this.subjectsList = res.data;
    },

    // 获取目录页面
    async getDirecotrysList() {
      const res = await simple({
        pagesize: 999,
        subjectID: this.testForm.subjectID,
      });
      this.directorysList = res.data.items;
      const res1 = await tagsList({
        pagesize: 999,
        subjectID: this.testForm.subjectID,
      });
      this.tagsList = res1.data.items;
    },

    // 获取企业列表
    async getCompanyList() {
      const res = await list({ pagesize: 999 });
      this.companysList = res.data.items;
    },

    // 增加选项按钮
    addQuestion() {
      this.testForm.options.splice(this.testForm.options.length, 0, {
        code: String.fromCharCode(
          "A".charCodeAt(0) + this.testForm.options.length
        ), // 代码
        title: "", // 标题
        img: "", // 图片URL
        isRight: false, // 是否正确答案
      });
    },

    // 获取详情  如果 localStorage 里面存了 questID属性的 id  name就渲染
    async addQuestionDetail() {
      let id = localStorage.getItem("questID") || this.$route.params.id;
      if (localStorage.getItem("questID") || this.$route.params.id) {
        const res = await addQuestionDetail({ id });
        this.testForm = {
          ...res.data,
          difficulty: +res.data.difficulty,
          questionType: +res.data.questionType,
        };
        this.getDirecotrysList();
        this.$set(this.testForm, "tags", this.testForm.tags.split(","));
        localStorage.removeItem("questID");
      }
    },
  },
};
</script>

<style scoped>
:deep(.el-upload) {
  width: 150px;
  height: 50px;
}
:deep(.el-upload img) {
  width: 150px;
  height: 50px;
}

:deep(.el-input__inner) {
  width: 500px;
}
:deep(.txt .el-input__inner) {
  width: 150px;
}
:deep(.txt240 .el-input__inner) {
  width: 240px;
}
:deep(.el-row > .el-input) {
  width: 250px;
  margin-top: 10px;
}

:deep(.edit_container) {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
:deep(.ql-editor) {
  height: 200px;
}
:deep(.el-upload) {
  position: relative;
  top: -44px;
  left: 322px;
}

:deep(.el-upload .up) {
  position: absolute;
  font-size: 16px;
  left: 40px;
  line-height: 50px;
}

:deep(.avatar-uploader .el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
:deep(.avatar-uploader .el-upload:hover) {
  border-color: #409eff;
}
:deep(.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
:deep(.avatar) {
  width: 150px;
  height: 50px;
  display: block;
}
:deep(.plus) {
  width: 150px;
  height: 50px;
}

:deep(.span) {
  position: absolute;
  line-height: 50px;
  left: 45px;
  font-size: 16px;
}
:deep(.close) {
  position: absolute;
  line-height: 50px;
  top: -18px;
  left: 133px;
  font-size: 16px;
}
</style>
